var echarts = require('echarts');


angular
    .module('baocloud.components.ngecharts', [])
    .directive('ngecharts', ngecharts);

function ngecharts() {
    var directive = {
        restrict: 'AE',
        replace: true,
        scope: {
            options: '=?'
        },
        templateUrl: 'ngecharts/ngecharts.html',
        link: link
    };
    return directive;
}

function link(scope, element) {
    var chart = null;

    function init() {
        if (!scope.options) return;
        console.log('char-->',element.find('.chart-container'));
        var chartObj = echarts.init(element.find('.chart-container')[0], 'macarons');
        scope.$emit('chartsReady', chartObj);
        return chartObj;
    }

    function onDatasetsChanged(newVal, oldVal) {
        console.log("newVal------>",newVal);
        console.log("oldVal------>",oldVal);
        console.log("newVal&&oldVal------>",angular.equals(newVal, oldVal));
        
        if (angular.equals(newVal, oldVal)) return;
        if(!chart){
            chart = init();
        }
        chart.setOption(newVal, true);
        angular.element(window).bind('resize', function () {
            chart.resize();
            console.log("resize------>",element);
        });
    }
    scope.$watch('options', onDatasetsChanged, true);
}